package com.ruoyi.stuSys.controller;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import javax.servlet.http.HttpServletResponse;

import freemarker.template.Template;
import freemarker.template.TemplateExceptionHandler;
import net.coobird.thumbnailator.Thumbnails;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.stuSys.domain.StuInfo;
import com.ruoyi.stuSys.service.IStuInfoService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import freemarker.template.Configuration;

/**
 * 学生学籍信息管理Controller
 * 
 * @author GG
 * @date 2024-08-21
 */
@RestController
@RequestMapping("/stuSys/stuInfo")
public class StuInfoController extends BaseController
{
    @Autowired
    private IStuInfoService stuInfoService;

    private Configuration config;

    public StuInfoController(){
        config = new Configuration(Configuration.VERSION_2_3_23);
        config.setDefaultEncoding("utf-8");
    }

    /**
     * 查询学生学籍信息管理列表
     */
    @PreAuthorize("@ss.hasPermi('stuSys:stuInfo:list')")
    @GetMapping("/list")
    public TableDataInfo list(StuInfo stuInfo)
    {
        startPage();
        List<StuInfo> list = stuInfoService.selectStuInfoList(stuInfo);
        return getDataTable(list);
    }

    /**
     * 导出学生学籍信息管理列表
     */
    @PreAuthorize("@ss.hasPermi('stuSys:stuInfo:export')")
    @Log(title = "学生学籍信息管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, StuInfo stuInfo)
    {
        List<StuInfo> list = stuInfoService.selectStuInfoList(stuInfo);
        ExcelUtil<StuInfo> util = new ExcelUtil<StuInfo>(StuInfo.class);
        util.exportExcel(response, list, "学生学籍信息管理数据");
    }

    /**
     * 获取学生学籍信息管理详细信息
     */
    @PreAuthorize("@ss.hasPermi('stuSys:stuInfo:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(stuInfoService.selectStuInfoById(id));
    }

    /**
     * 新增学生学籍信息管理
     */
    @PreAuthorize("@ss.hasPermi('stuSys:stuInfo:add')")
    @Log(title = "学生学籍信息管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody StuInfo stuInfo)
    {
        return toAjax(stuInfoService.insertStuInfo(stuInfo));
    }

    /**
     * 修改学生学籍信息管理
     */
    @PreAuthorize("@ss.hasPermi('stuSys:stuInfo:edit')")
    @Log(title = "学生学籍信息管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody StuInfo stuInfo)
    {
        return toAjax(stuInfoService.updateStuInfo(stuInfo));
    }

    /**
     * 删除学生学籍信息管理
     */
    @PreAuthorize("@ss.hasPermi('stuSys:stuInfo:remove')")
    @Log(title = "学生学籍信息管理", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(stuInfoService.deleteStuInfoByIds(ids));
    }

    //word操作
    @PreAuthorize("@ss.hasPermi('stuSys:stuInfo:query')")
    @GetMapping("/queryStu/{id}")
    public void queryStu(@PathVariable Long[] id, HttpServletResponse response) throws IOException {
        response.setContentType("application/zip");
        response.setHeader("Content-Disposition", "attachment; filename=reports.zip");
        try (ZipOutputStream zos = new ZipOutputStream(response.getOutputStream())) {
            for (Long sid : id) {
                StuInfo stuInfo = stuInfoService.selectStuInfoById(sid);

                Map<String, Object> dataMap = new HashMap<>();

                dataMap.put("Snum", stuInfo.getStudentNumber());
                dataMap.put("Name", stuInfo.getName());
                dataMap.put("Gen", stuInfo.getGender());
                dataMap.put("Pro", stuInfo.getProvinceOfOrigin());
                dataMap.put("Native", stuInfo.getNativePlace());
                dataMap.put("Major", stuInfo.getMajor());
                dataMap.put("Depart", stuInfo.getDepartment());
                dataMap.put("Score", stuInfo.getEntranceScore());
                dataMap.put("Phone", stuInfo.getPhoneNumber());
                dataMap.put("Person", stuInfo.getPersonalIntroduction());


                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
                Date date = stuInfo.getDateOfBirth();
                String[] dateStr = dateFormat.format(date).split("-");
                String normativeDate = dateFormat.format(date);
                dataMap.put("Y",dateStr[0]);
                dataMap.put("M",dateStr[1]);
                dataMap.put("D",dateStr[2]);
                dataMap.put("Birth", normativeDate);

                String stuPhoto=stuInfo.getPhoto();
                // 检查照片，如果上传了多张，则使用第一张
                if (stuPhoto != null && !stuPhoto.isEmpty()) {
                    String[] stuPicList = stuPhoto.replace("profile", "D:\\ruoyi\\uploadPath").split(",");
                    if (stuPicList.length > 0) {
                        dataMap.put("Pic", getImageStr(stuPicList[0]));
                    }
                }


                String fileName = "华北电力大学" + stuInfo.getName() + "学籍报告.doc";
                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                createWord(dataMap, "A1.ftl", byteArrayOutputStream);

                zos.putNextEntry(new ZipEntry(fileName));
                byteArrayOutputStream.writeTo(zos);
                zos.closeEntry();
            }
        }
    }

    public void createWord(Map<String, Object> dataMap, String templateName, OutputStream outputStream) throws IOException {
        config.setClassForTemplateLoading(this.getClass(), "/ftl");
        config.setTemplateExceptionHandler(TemplateExceptionHandler.IGNORE_HANDLER);
        Template template = null;
        if (templateName.endsWith(".ftl")) {
            templateName = templateName.substring(0, templateName.indexOf(".ftl"));
        }
        try {
            template = config.getTemplate(templateName + ".ftl");
        } catch (Exception e) {
            e.printStackTrace();
        }

        Writer out = new BufferedWriter(new OutputStreamWriter(outputStream));
        try {
            template.process(dataMap, out);
        } catch (Exception e) {
            e.printStackTrace();
        }
        out.flush();
    }

    public String getImageStr(String imgFile) {
        InputStream in = null;
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        byte[] data = null;
        try {
            // 使用 Thumbnailator 压缩图片
            Thumbnails.of(imgFile)
                    .scale(1.0) // 保持原始尺寸
                    .outputQuality(0.2) // 设置压缩质量 (0.75 代表压缩为原始质量的 75%)
                    .toOutputStream(outputStream);
            System.out.println("压缩中");
            data = outputStream.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        Base64.Encoder encoder = Base64.getEncoder();
        return encoder.encodeToString(data);
    }



}
